package com.ruoyi.wxorali.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.config.SystemConfig;
import com.ruoyi.wxorali.service.AliYunYuYinService;
import com.ruoyi.wxorali.service.MinioServletService;
import com.ruoyi.wxorali.utils.AliYunUtil;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.*;
import io.minio.*;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@RequiredArgsConstructor
public class MinioServletServiceImpl implements MinioServletService {
    @Resource
    private AliYunYuYinService aliYunYuYinService;
    @Override
    public void minioText(File nfile) {

        // 创建 Minio 客户端
        BufferedReader br = null;
        FileInputStream fis = null;
        InputStreamReader reader = null;
        try {
            fis = new FileInputStream(nfile);
            reader = new InputStreamReader(fis, "GBK");
            reader = new InputStreamReader(fis, "UTF-8");// 编码格式必须和文件的一致
            BufferedReader bufferedReader = new BufferedReader(reader);
            MinioClient minioClient = MinioClient.builder()
                    .endpoint("120.79.47.215",9000,false)
                    .credentials("minioadmin", "minioadmin")
                    .build();
            // 检查存储桶是否存在，如果不存在则创建
            String bucketName = "telegram";
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            String lineTxt = null;
            String resourceRoot = SystemConfig.getUploadMinio();
            while ((lineTxt = bufferedReader.readLine()) != null) {
                if (StringUtils.isNotEmpty(lineTxt)){
                    File folder = new File(resourceRoot+"/"+lineTxt);
                    uploadFolder(minioClient, bucketName, folder, lineTxt);
                }

            }


            System.out.println("图片上传成功！");
        } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException e) {
            System.out.println("图片上传失败: " + e.getMessage());
        }
    }

    /**
     * minio图片上传
     * @param minioClient
     * @param bucketName
     * @param folder
     * @param prefix
     * @throws IOException
     * @throws MinioException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public void uploadFolder(MinioClient minioClient, String bucketName, File folder, String prefix) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        File[] files = folder.listFiles();
        if (files != null) {
            Map<String, Boolean> mapNotUp = new HashMap<>();
            // 先去检测文件到底符不符合上传的条件
            List<File> imagesList = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                if (!files[i].isDirectory()) {
                imagesList.add(files[i]);
                if (i % 2 == 0) {
                    try {
                        JSONArray obj = aliYunYuYinService.generateImage(imagesList);
                        mapNotUp.putAll(AliYunUtil.resolvingJSON(obj));
                        imagesList = new ArrayList<>();
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
            }
            if (imagesList.size() > 0) {
                try {
                    JSONArray obj = aliYunYuYinService.generateImage(imagesList);
                    mapNotUp.putAll( AliYunUtil.resolvingJSON(obj));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            for (File file : files) {
                if (file.isDirectory()) {
                    // 如果是子文件夹，递归上传
                    String subFolderPrefix = prefix + file.getName() + "/";
                    uploadFolder(minioClient, bucketName, file, subFolderPrefix);
                } else {

                    if (!mapNotUp.containsKey(file.getName())){
                        // 如果是文件，上传到 MinIO
                        String objectName = prefix + "/" + file.getName();
                        UploadObjectArgs.Builder builder = UploadObjectArgs.builder();
                        builder.bucket(bucketName);
                        builder.object(objectName);
                        builder.filename(file.getPath());
                        UploadObjectArgs uploadObjectArgs = builder.build();
                        minioClient.uploadObject(uploadObjectArgs);
                    }
                }
            }

        }

    }


}


